package tmall.domain.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tmall.common.config.AppConst;
import tmall.common.controller.BaseController;
import tmall.common.dto.PageDTO;
import tmall.common.dto.ResponseResult;
import tmall.common.util.ApiRet;
import tmall.common.util.IsAdmin;
import tmall.common.vo.PageVO;
import tmall.domain.entity.Category;
import tmall.domain.service.CategoryService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api("商品类目")
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController {

    @Resource
    private CategoryService categoryService;

    @Value("${image.path}")
    private String imgPath;

    @GetMapping("/getAll")
    @ApiOperation(value = "获取所有商品类目", httpMethod = "GET")
    public ResponseResult getAll() throws Exception {
        List list = categoryService.findAllBy(null);
        return ApiRet.success(list);
    }

    @PostMapping("/list")
    @ApiOperation(value = "分页查询类目", httpMethod = "POST")
    public ResponseResult list(PageVO pageVO) {
        PageDTO result = categoryService.list(pageVO.getPageNum(), pageVO.getPageSize(), pageVO.getKeyWord());
        return ApiRet.success(result);
    }

    @PostMapping("/add")
    @IsAdmin
    @ApiOperation(value = "添加类目", httpMethod = "POST")
    public ResponseResult add(Category entity) {
        entity.setImageSrc(AppConst.CATEGORY_IMG_FOLDER + entity.getImageSrc());
        categoryService.insert(entity);
        return ApiRet.success("成功");
    }

    @PostMapping("/edit")
    @ApiOperation(value = "编辑类目", httpMethod = "POST")
    public ResponseResult edit(Category entity) {
        entity.setImageSrc(AppConst.CATEGORY_IMG_FOLDER + entity.getImageSrc());
        categoryService.update(entity);
        return ApiRet.success("成功");
    }

    @ResponseBody
    @PostMapping(value = "/uploadImg")
    @ApiOperation(value = "上传图片", httpMethod = "POST")
    public ResponseResult uploadCategoryImage(@RequestParam MultipartFile file) throws IOException {

        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        String fileName = UUID.randomUUID() + extension;
        String filePath = System.getProperty("user.dir") + imgPath + AppConst.CATEGORY_IMG_FOLDER + fileName;

        super.uploadImg(filePath, file);
        return ApiRet.success(fileName);
    }


    @GetMapping("/delete")
    @ApiOperation(value = "删除类目", httpMethod = "GET")
    public ResponseResult delete(Long id) throws Exception {
        int ret = categoryService.delete(id);
        return ApiRet.success("成功");
    }
}
